# main_window.py
from PySide6.QtWidgets import (
    QMainWindow, QDockWidget, QStatusBar, QMenu, QFileDialog, QInputDialog,
    QMessageBox, QTabWidget, QToolBar, QSplitter
)
from PySide6.QtCore import Qt
from PySide6.QtGui import QAction, QIcon, QActionGroup
import os
import sys
from ui.project_tree import ProjectTreeDock
from ui.table_window import TableWindow
from ui.data_import_dialog import DataImportDialog
from ui.vertical_visualization import VerticalVisualizationDock
from ui.horizontal_visualization import HorizontalVisualizationWidget
from utils.data_manager import DataManager
from utils.setting_manager import SettingsManager


class MainWindow(QMainWindow):
    """主窗口类"""

    def __init__(self):
        super().__init__()# 初始化父类

        # 初始化设置管理器
        self.settings_manager = SettingsManager()

        # 初始化数据管理器
        self.data_manager = DataManager()
        self.data_manager.data_updated.connect(self._on_data_updated)

        # 初始化UI
        self._init_ui()

        # 加载应用设置
        self._load_settings()

        # 连接信号和槽
        self._connect_signals()

        # 启动时创建示例数据
        self._create_sample_data_if_empty()

    def _init_ui(self):
        """初始化UI组件"""
        # 设置窗口标题和大小
        self.setWindowTitle("井数据可视化程序")
        self.resize(1200, 800)

        # 创建中心部件 - 使用QSplitter允许用户调整视图比例
        self.central_splitter = QSplitter(Qt.Horizontal)
        self.setCentralWidget(self.central_splitter)

        # 添加水平可视化标签页
        self.horizontal_visualization = HorizontalVisualizationWidget()
        self.central_splitter.addWidget(self.horizontal_visualization)

        # 创建项目树停靠窗口
        self.project_tree_dock = ProjectTreeDock()
        self.addDockWidget(self.project_tree_dock.dock_area, self.project_tree_dock)

        # 创建竖向可视化停靠窗口
        self.vertical_visualization_dock = VerticalVisualizationDock()
        self.addDockWidget(self.vertical_visualization_dock.dock_area, self.vertical_visualization_dock)

        # 设置状态栏
        self.statusBar().showMessage("就绪")

        # 创建菜单栏
        self._create_menu_bar()

        # 创建工具栏
        self._create_tool_bar()

    def _create_menu_bar(self):
        """创建菜单栏"""
        # 文件菜单
        file_menu = self.menuBar().addMenu("文件")

        # 新建项目动作
        new_project_action = QAction("新建项目", self)
        new_project_action.setShortcut("Ctrl+N")
        new_project_action.triggered.connect(self._new_project)
        file_menu.addAction(new_project_action)

        # 打开项目动作
        open_project_action = QAction("打开项目", self)
        open_project_action.setShortcut("Ctrl+O")
        open_project_action.triggered.connect(self._open_project)
        file_menu.addAction(open_project_action)

        # 保存项目动作
        save_project_action = QAction("保存项目", self)
        save_project_action.setShortcut("Ctrl+S")
        save_project_action.triggered.connect(self._save_project)
        file_menu.addAction(save_project_action)

        file_menu.addSeparator()

        # 导入数据动作
        import_action = QAction("导入数据", self)
        import_action.setShortcut("Ctrl+I")
        import_action.triggered.connect(self._import_data)
        file_menu.addAction(import_action)

        # 导出数据动作
        export_action = QAction("导出数据", self)
        export_action.setShortcut("Ctrl+E")
        export_action.triggered.connect(self._export_data)
        file_menu.addAction(export_action)

        file_menu.addSeparator()

        # 退出动作
        exit_action = QAction("退出", self)
        exit_action.setShortcut("Ctrl+Q")
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)

        # 视图菜单
        view_menu = self.menuBar().addMenu("视图")

        # 显示项目树动作
        show_project_tree_action = QAction("项目树", self)
        show_project_tree_action.setCheckable(True)
        show_project_tree_action.setChecked(True)
        show_project_tree_action.triggered.connect(self._toggle_project_tree)
        view_menu.addAction(show_project_tree_action)

        # 显示竖向可视化动作
        show_vertical_vis_action = QAction("竖向可视化", self)
        show_vertical_vis_action.setCheckable(True)
        show_vertical_vis_action.setChecked(True)
        show_vertical_vis_action.triggered.connect(self._toggle_vertical_vis)
        view_menu.addAction(show_vertical_vis_action)

        # 显示水平可视化动作
        show_horizontal_vis_action = QAction("水平可视化", self)
        show_horizontal_vis_action.setCheckable(True)
        show_horizontal_vis_action.setChecked(True)
        show_horizontal_vis_action.triggered.connect(self._toggle_horizontal_vis)
        view_menu.addAction(show_horizontal_vis_action)

        view_menu.addSeparator()

        # 排列窗口动作
        arrange_action = QAction("排列窗口", self)
        arrange_action.triggered.connect(self._arrange_windows)
        view_menu.addAction(arrange_action)

        # 窗口菜单
        window_menu = self.menuBar().addMenu("窗口")

        # 层叠窗口动作
        cascade_action = QAction("层叠窗口", self)
        cascade_action.triggered.connect(self._cascade_windows)
        window_menu.addAction(cascade_action)

        # 并排窗口动作
        tile_action = QAction("并排窗口", self)
        tile_action.triggered.connect(self._tile_windows)
        window_menu.addAction(tile_action)

        # 帮助菜单
        help_menu = self.menuBar().addMenu("帮助")

        # 关于动作
        about_action = QAction("关于", self)
        about_action.triggered.connect(self._show_about)
        help_menu.addAction(about_action)

        # 使用帮助动作
        help_action = QAction("使用帮助", self)
        help_action.triggered.connect(self._show_help)
        help_menu.addAction(help_action)

    def _create_tool_bar(self):
        """创建工具栏"""
        tool_bar = QToolBar("主工具栏", self)
        self.addToolBar(tool_bar)

        # 新建项目按钮
        new_project_action = QAction(QIcon(":/icons/new-project.svg"), "新建项目", self)
        new_project_action.triggered.connect(self._new_project)
        tool_bar.addAction(new_project_action)

        # 打开项目按钮
        open_project_action = QAction(QIcon(":/icons/open-project.svg"), "打开项目", self)
        open_project_action.triggered.connect(self._open_project)
        tool_bar.addAction(open_project_action)

        # 保存项目按钮
        save_project_action = QAction(QIcon(":/icons/save-project.svg"), "保存项目", self)
        save_project_action.triggered.connect(self._save_project)
        tool_bar.addAction(save_project_action)

        tool_bar.addSeparator()

        # 导入数据按钮
        import_action = QAction(QIcon(":/icons/import.svg"), "导入数据", self)
        import_action.triggered.connect(self._import_data)
        tool_bar.addAction(import_action)

        # 导出数据按钮
        export_action = QAction(QIcon(":/icons/export.svg"), "导出数据", self)
        export_action.triggered.connect(self._export_data)
        tool_bar.addAction(export_action)

        tool_bar.addSeparator()

        # 可视化按钮组
        vis_group = QActionGroup(self)
        vis_group.setExclusive(True)

        vertical_vis_action = QAction(QIcon(":/icons/vertical-vis.svg"), "竖向可视化", self)
        vertical_vis_action.setCheckable(True)
        vertical_vis_action.triggered.connect(lambda: self._switch_visualization_mode("vertical"))
        vis_group.addAction(vertical_vis_action)
        tool_bar.addAction(vertical_vis_action)

        horizontal_vis_action = QAction(QIcon(":/icons/horizontal-vis.svg"), "水平可视化", self)
        horizontal_vis_action.setCheckable(True)
        horizontal_vis_action.triggered.connect(lambda: self._switch_visualization_mode("horizontal"))
        vis_group.addAction(horizontal_vis_action)
        tool_bar.addAction(horizontal_vis_action)

        # 默认选择竖向可视化
        vertical_vis_action.setChecked(True)

    def _connect_signals(self):
        """连接信号和槽"""
        # 连接项目树的信号
        self.project_tree_dock.visualization_requested.connect(self._show_visualization)
        self.project_tree_dock.open_table_requested.connect(self._open_table)
        self.project_tree_dock.well_renamed.connect(self._on_well_renamed)
        self.project_tree_dock.well_deleted.connect(self._on_well_deleted)

    def _new_project(self):
        """创建新项目"""
        if self._check_project_modified():
            project_path = QFileDialog.getExistingDirectory(
                self, "选择项目文件夹", os.path.expanduser("~")
            )
            if project_path:
                self.data_manager.set_project_path(project_path)
                self.settings_manager.set_last_project_path(project_path)
                self.statusBar().showMessage(f"新项目已创建: {project_path}")
                self.project_tree_dock.refresh()

    def _open_project(self):
        """打开现有项目"""
        if self._check_project_modified():
            project_path = QFileDialog.getExistingDirectory(
                self, "选择项目文件夹", os.path.expanduser("~")
            )
            if project_path:
                self.data_manager.set_project_path(project_path)
                self.settings_manager.set_last_project_path(project_path)
                self.statusBar().showMessage(f"项目已打开: {project_path}")
                self.project_tree_dock.refresh()

    def _save_project(self):
        """保存项目"""
        project_path = self.data_manager.get_project_path()
        if not project_path:
            self._new_project()
        else:
            # 数据管理器会自动保存更改
            self.statusBar().showMessage(f"项目已保存: {project_path}")

    def _import_data(self):
        """导入数据"""
        file_path, _ = QFileDialog.getOpenFileName(#解释_:选择文件
            self, "选择数据文件", "",
            "所有支持的文件 (*.csv *.xlsx *.txt);;"
            "CSV文件 (*.csv);;"
            "Excel文件 (*.xlsx);;"
            "文本文件 (*.txt)"
        )

        if file_path:
            try:
                # 读取文件数据
                _, ext = os.path.splitext(file_path)#解释_:获取文件扩展名
                if ext.lower() == '.txt':
                    data = self.data_manager._read_text_file(file_path)
                elif ext.lower() == '.csv':
                    data = self.data_manager._read_csv_file(file_path)
                elif ext.lower() in ['.xlsx', '.xls']:
                    data = self.data_manager._read_excel_file(file_path)
                else:
                    QMessageBox.warning(self, "警告", f"不支持的文件格式: {ext}")
                    return

                if data is None or data.empty:
                    QMessageBox.warning(self, "警告", f"文件解析结果为空: {file_path}")
                    return

                # 弹出数据导入对话框
                dialog = DataImportDialog(data, self)
                if dialog.exec_():
                    # 获取处理后的数据
                    processed_data = dialog.processed_data

                    # 获取默认井名（文件名去掉扩展名）
                    default_well_name = os.path.splitext(os.path.basename(file_path))[0]

                    # 让用户可以修改井名
                    well_name, ok = QInputDialog.getText(
                        self, "设置井名", "请输入井名:",
                        text=default_well_name
                    )

                    if ok and well_name:
                        if self.data_manager.add_well(well_name, processed_data):
                            self.statusBar().showMessage(f"成功导入数据: {well_name}")
                            self.project_tree_dock.refresh()

                            # 更新可视化
                            self._show_visualization(well_name)
                        else:
                            QMessageBox.warning(self, "导入失败", "导入数据失败")
            except Exception as e:
                QMessageBox.critical(self, "导入失败", f"导入数据失败: {str(e)}")

    def _export_data(self):
        """导出数据"""
        # 获取当前选中的井
        selected_items = self.project_tree_dock.tree.selectedItems()
        if not selected_items:
            QMessageBox.information(self, "导出失败", "请先选择要导出的井")
            return

        item = selected_items[0]
        item_data = item.data(0, Qt.UserRole)

        if not item_data or item_data["type"] != "well":
            QMessageBox.information(self, "导出失败", "请选择井节点进行导出")
            return

        well_name = item_data["name"]

        export_path, _ = QFileDialog.getSaveFileName(
            self, "保存文件", f"{well_name}.xlsx",
            "Excel 文件 (*.xlsx);;CSV 文件 (*.csv)"
        )

        if export_path:
            try:
                self.data_manager.export_well_data(well_name, export_path)
                self.statusBar().showMessage(f"成功导出数据到: {export_path}")
            except Exception as e:
                QMessageBox.critical(self, "导出失败", f"导出数据时发生错误: {str(e)}")

    def _toggle_project_tree(self, visible):
        """显示/隐藏项目树"""
        if visible:
            self.project_tree_dock.show()
        else:
            self.project_tree_dock.hide()

    def _toggle_vertical_vis(self, visible):
        """显示/隐藏竖向可视化"""
        if visible:
            self.vertical_visualization_dock.show()
        else:
            self.vertical_visualization_dock.hide()

    def _toggle_horizontal_vis(self, visible):
        """显示/隐藏水平可视化"""
        if visible:
            self.horizontal_visualization.show()
        else:
            self.horizontal_visualization.hide()

    def _arrange_windows(self):
        """排列窗口"""
        self.setDockNestingEnabled(True)

        # 重置所有停靠窗口
        self.removeDockWidget(self.project_tree_dock)
        self.removeDockWidget(self.vertical_visualization_dock)

        # 重新添加停靠窗口
        self.addDockWidget(Qt.LeftDockWidgetArea, self.project_tree_dock)
        self.addDockWidget(Qt.RightDockWidgetArea, self.vertical_visualization_dock)

    def _cascade_windows(self):
        """层叠窗口"""
        self.window().cascadeSubWindows()

    def _tile_windows(self):
        """并排窗口"""
        self.window().tileSubWindows()

    def _show_about(self):
        """显示关于对话框"""
        QMessageBox.about(
            self,
            "关于井数据可视化程序",
            "井数据可视化程序 v1.0\n\n"
            "这是一个用于井数据可视化和分析的程序。\n"
            "支持导入多种格式的井数据，进行可视化分析和导出。"
        )

    def _show_help(self):
        """显示帮助对话框"""
        QMessageBox.information(
            self,
            "使用帮助",
            "井数据可视化程序使用帮助\n\n"
            "1. 导入数据：通过文件菜单或工具栏导入CSV或Excel格式的井数据\n"
            "2. 浏览数据：在项目树中查看已导入的井和曲线\n"
            "3. 可视化：双击井节点或使用工具栏进行数据可视化\n"
            "4. 导出数据：选择井节点后通过文件菜单或工具栏导出数据\n"
            "5. 窗口布局：通过视图菜单调整窗口布局"
        )

    def _show_visualization(self, well_name):
        """显示可视化"""
        data = self.data_manager.get_well_data(well_name)

        if data is not None:
            # 更新竖向可视化
            self.vertical_visualization_dock.update_data(well_name, data)

            # 更新水平可视化
            self.horizontal_visualization.update_data(well_name, data)

            self.statusBar().showMessage(f"显示井数据: {well_name}")
        else:
            QMessageBox.warning(self, "数据不存在", f"井 '{well_name}' 的数据不存在")

    def _open_table(self, well_name):
        """打开表格窗口"""
        data = self.data_manager.get_well_data(well_name)

        if data is not None:
            table_window = TableWindow(well_name, data, self)
            table_window.show()
        else:
            QMessageBox.warning(self, "数据不存在", f"井 '{well_name}' 的数据不存在")

    def _on_data_updated(self, well_name):
        """处理数据更新事件"""
        self.statusBar().showMessage(f"数据已更新: {well_name}")
        self.project_tree_dock.refresh()

    def _on_well_renamed(self, old_name, new_name):
        """处理井重命名事件"""
        self.statusBar().showMessage(f"井已重命名: {old_name} -> {new_name}")

    def _on_well_deleted(self, well_name):
        """处理井删除事件"""
        self.statusBar().showMessage(f"井已删除: {well_name}")

    def _switch_visualization_mode(self, mode):
        """切换可视化模式"""
        if mode == "vertical":
            self.vertical_visualization_dock.show()
            self.horizontal_visualization.hide()
        elif mode == "horizontal":
            self.vertical_visualization_dock.hide()
            self.horizontal_visualization.show()

    def _check_project_modified(self):
        """检查项目是否有修改并询问用户"""
        # 简化实现，实际应检查数据是否有修改
        return True

    def _load_settings(self):
        """加载应用设置"""
        # 恢复窗口大小和位置
        geometry = self.settings_manager.get_window_geometry()
        if geometry:
            self.restoreGeometry(geometry)

        # 恢复窗口状态（停靠窗口位置等）
        state = self.settings_manager.get_window_state()
        if state:
            self.restoreState(state)

        # 恢复上次打开的项目路径
        last_project_path = self.settings_manager.get_last_project_path()
        if last_project_path:
            self.data_manager.set_project_path(last_project_path)
            self.project_tree_dock.refresh()

    def _create_sample_data_if_empty(self):
        """如果没有数据，创建示例数据"""
        if not self.data_manager.get_well_list():
            # 创建几个示例井数据
            import pandas as pd
            for i in range(3):
                well_name = f"井{i + 1}"
                sample_data = pd.DataFrame({
                    '深度': [100, 200, 300],
                    '曲线1': [1, 2, 3],
                    '曲线2': [4, 5, 6]
                })
                self.data_manager.add_well(well_name, sample_data)

            # self.project_tree_dock.refresh()
            self.statusBar().showMessage("已创建示例数据")

    def closeEvent(self, event):
        """处理窗口关闭事件"""
        if self._check_project_modified():
            # 保存应用设置
            self.settings_manager.set_window_geometry(self.saveGeometry())
            self.settings_manager.set_window_state(self.saveState())

            event.accept()
        else:
            event.ignore()